//
//  LSYReadViewController.m
//  LSYReader
//
//  Created by Labanotation on 16/5/30.
//  Copyright © 2016年 okwei. All rights reserved.
//

#import "LSYReadViewController.h"

#import "LSYReadParser.h"
#import "LSYReadConfig.h"
#import "ReedBookFirstAdvViewController.h"


@interface LSYReadViewController ()<LSYReadViewControllerDelegate>

@end

@implementation LSYReadViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self prefersStatusBarHidden];
    [self.view setBackgroundColor:[LSYReadConfig shareInstance].theme];
    [self.view addSubview:self.readView];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTheme:) name:LSYThemeNotification object:nil];
    //ui布局
    [self creatUI];
}


-(void)creatUI
{
    
    self.isFirst = YES;
    
//    [self.view addGestureRecognizer:({
//        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
////        tap.delegate = self;
//        tap;
//    })];
    
    //阅读q内容
    _readView = [[LSYReadView alloc] initWithFrame:CGRectMake(LeftSpacing,TopSpacing, self.view.frame.size.width-LeftSpacing-RightSpacing, self.view.frame.size.height-TopSpacing-BottomSpacing)];
   
    _readView.content = _content;
    _readView.delegate = self;
    [self.view addSubview:_readView];
    
    //电量
    _batteryView = [[DCBatteryView alloc]initWithLineColor:[UIColor blackColor]];
    [self.view addSubview:self.batteryView];
    _batteryView.lineColor = TextColor1;
    [self.batteryView runProgress:[self getCurrentBatteryLevel]];
    
    /**
     //章节名称
     */
    UILabel *nameLable = [[UILabel alloc]init];
    nameLable.text = self.recordModel.chapterModel.title;
    nameLable.textColor = TextColor1;
    nameLable.font = [UIFont systemFontOfSize:10];
    self.nameLable = nameLable;
    [self.view addSubview:nameLable];
    
    //章节首页名称
    UILabel *gigNameLable = [[UILabel alloc]init];
    gigNameLable.text = self.recordModel.chapterModel.title;
    gigNameLable.textColor = CSColorFromRGB(0x010100);
    gigNameLable.font = [UIFont systemFontOfSize:22];
    gigNameLable.textAlignment = NSTextAlignmentCenter;
    self.gigNameLable = gigNameLable;
    [self.view addSubview:gigNameLable];
    self.gigNameLable.hidden = !self.isFirst;

    
    //章节量
    UILabel *howLable = [[UILabel alloc]init];
    howLable.text = [NSString stringWithFormat:@"%.2f%%",(CGFloat)(self.recordModel.chapter+1)/(CGFloat)self.recordModel.chapterCount *100] ;
    howLable.textColor = TextColor1;
    howLable.font = [UIFont systemFontOfSize:10];
    self.howLable = howLable;
    [self.view addSubview:howLable];
    
    //时间
    UILabel *timeLable = [[UILabel alloc]init];
    timeLable.textColor = TextColor1;
    timeLable.font = [UIFont systemFontOfSize:10];
    self.timeLable = timeLable;
    [self.view addSubview:timeLable];
    //处理
    NSDateFormatter *objDateformat1 = [[NSDateFormatter alloc] init];
    [objDateformat1 setDateFormat:@"HH:mm"];
    NSString *timestamp1 = [objDateformat1 stringFromDate: [NSDate date]];
    timeLable.text = timestamp1;
    
    //广告
    _adviImageView = [[UIImageView alloc]init];
    _adviImageView.image = self.recordModel.page%2==0?[UIImage imageNamed:@"底部广告2"]:[UIImage imageNamed:@"底部广告"];
    _adviImageView.userInteractionEnabled = YES;
    [self.view addSubview:_adviImageView];
    _adviImageView.hidden = self.isVip;
    
    UILabel *advLable = [[UILabel alloc]init];
    advLable.text = @"广告";
    advLable.textAlignment = NSTextAlignmentCenter;
    advLable.backgroundColor = CSColorFromRGBA(0x000000, 0.5);
    advLable.layer.cornerRadius = 2;
    advLable.clipsToBounds = YES;
    advLable.textColor = CSWhiteColor;
    advLable.font = [UIFont systemFontOfSize:12];
    self.advLable = advLable;
    [self.adviImageView addSubview:advLable];
    
//    _bottomView = [[ReadFooterView alloc]initWithFrame:CGRectMake(0, kScreenH - (Iphone5?70:90), kScreenW,self.isVip?adaptTabBar:49)];
//    _bottomView.hidden = YES;
//    [self.view addSubview:_bottomView];
//    
//    //顶部
//    _topView = [[CZQCustomNavView alloc]initWithFrame:CGRectMake(0, -toolH, kScreenW,toolH)];
//    [self.view addSubview:_topView];
//        _topView.hidden = YES;
//    _topView.bgView.hidden = YES;
//    _topView.backgroundColor = CSColorFromRGB(0x333333);
//    [_topView.rightBtn setImage:@"分享"];
//    _topView.rightBtn.hidden = NO;
//    
//    [_bottomView mas_remakeConstraints:^(MASConstraintMaker *make) {
//        
//        make.top.mas_equalTo(self.adviImageView.mas_top);
//        make.left.width.right.mas_equalTo(self.view);
//        make.height.mas_equalTo(self.isVip?adaptTabBar:49);
//        
//    }];
    
    //尺寸布局
    [_nameLable mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(self.view).offset(AdaptStatusBar);
        make.left.mas_equalTo(self.view).offset(12);
        
    }];
    
    [_gigNameLable mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(self.view).offset(adaptNavagationBar);
        make.left.mas_equalTo(self.view).offset(12);
        make.right.mas_equalTo(self.view).offset(-12);
        
    }];
    
    [_readView mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        
        if (self.isFirst) {
            make.top.mas_equalTo(self.gigNameLable.mas_bottom).offset(25);
        }else
        {
            make.top.mas_equalTo(self.nameLable.mas_bottom).offset(14);
        }
        make.left.mas_equalTo(self.view).offset(12);
        make.right.mas_equalTo(self.view).offset(-15);
        
    }];
    
    
    [_howLable mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(self.readView.mas_bottom).offset(25);
        make.left.mas_equalTo(self.view).offset(12);
        make.height.mas_equalTo(10);
        
    }];
    
    [_timeLable mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.centerY.mas_equalTo(self.howLable);
        make.height.mas_equalTo(15);
        make.right.mas_equalTo(self.batteryView.mas_left).offset(-5);
        
    }];
    
    [_batteryView mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.centerY.mas_equalTo(self.howLable);
        make.right.mas_equalTo(self.readView);
        make.height.mas_equalTo(10);
        make.width.mas_equalTo(60);
        
    }];
    
    [_adviImageView mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.left.bottom.width.mas_equalTo(self.view);
        make.top.mas_equalTo(self.howLable.mas_bottom).offset(10);
        make.height.mas_equalTo(self.isVip?0:(Iphone5?70:90));
        
    }];
    
    [_advLable mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.width.mas_equalTo(35);
        make.height.mas_equalTo(16);
        make.top.mas_equalTo(self.adviImageView).offset(5);
        make.right.mas_equalTo(self.adviImageView).offset(-5);
        
    }];
    
    [self.view setNeedsLayout];
    [self.view layoutIfNeeded];
    
    
    LSYReadConfig *config = [LSYReadConfig shareInstance];
    _readView.frameRef = [LSYReadParser parserContent:_content config:config bouds:CGRectMake(0,0, _readView.frame.size.width, _readView.frame.size.height)];
    
    
    [LSYReadConfig shareInstance].contentRect = _readView.frame;
    
    
    
    self.view.backgroundColor =  [LSYReadConfig shareInstance].theme;
    
    if ([LSYReadConfig shareInstance].theme != CSWhiteColor) {
        
        self.nameLable.textColor = CSColorFromRGB(0x757575);
        self.gigNameLable.textColor = CSColorFromRGB(0x757575);
        self.timeLable.textColor = CSColorFromRGB(0x757575);
        self.howLable.textColor = CSColorFromRGB(0x757575);
        self.batteryView.lineColor = CSColorFromRGB(0x757575);
        
    }else
    {
        self.nameLable.textColor = TextColor1;
        self.gigNameLable.textColor = CSColorFromRGB(0x010100);
        self.timeLable.textColor = TextColor1;
        self.howLable.textColor = TextColor1;
        self.batteryView.lineColor = TextColor1;
    }
    
   
    
    
}

#pragma mark  - event
-(void)tap:(UITapGestureRecognizer *)tap
{
    CGPoint point = [tap locationInView:self.view];
    if(point.x < kScreenW * 0.3 || point.x > kScreenW * 0.7 || point.y <kScreenH * 0.3 || point.y > kScreenH * 0.7)
        return;
    if(!self.topView.hidden)
    {
        //显示了则退回去
        [UIView animateWithDuration:0.3 animations:^{
            self.topView.transform = CGAffineTransformIdentity;
            self.bottomView.transform = CGAffineTransformIdentity;
        }completion:^(BOOL finished) {
            self.topView.hidden = YES;
            self.bottomView.hidden = YES;
        }];
    }else
    {
        //没显示则显示出来
        self.topView.hidden = NO;
        self.bottomView.hidden = NO;
        [UIView animateWithDuration:0.3 animations:^{
            self.topView.transform = CGAffineTransformMakeTranslation(0, toolH);
            self.bottomView.transform = CGAffineTransformMakeTranslation(0,-(adaptTabBar));
        }];
    }
//    self.showBar = !self.showBar;
//    //更新状态栏是不是显示
//    [[UIApplication sharedApplication] setStatusBarHidden:!self.showBar];
}

-(void)changeTheme:(NSNotification *)no
{
    [LSYReadConfig shareInstance].theme = no.object;
    [self.view setBackgroundColor:[LSYReadConfig shareInstance].theme];
    if ([LSYReadConfig shareInstance].theme != CSWhiteColor) {
        
        self.nameLable.textColor = CSColorFromRGB(0x757575);
        self.gigNameLable.textColor = CSColorFromRGB(0x757575);
        self.timeLable.textColor = CSColorFromRGB(0x757575);
        self.howLable.textColor = CSColorFromRGB(0x757575);
        self.batteryView.lineColor = CSColorFromRGB(0x757575);
        
    }else
    {
        self.nameLable.textColor = TextColor1;
        self.gigNameLable.textColor = CSColorFromRGB(0x010100);
        self.timeLable.textColor = TextColor1;
        self.howLable.textColor = TextColor1;
        self.batteryView.lineColor = TextColor1;
    }
}



-(void)readViewEditeding:(LSYReadViewController *)readView
{
    if ([self.delegate respondsToSelector:@selector(readViewEditeding:)]) {
        [self.delegate readViewEditeding:self];
    }
}
-(void)readViewEndEdit:(LSYReadViewController *)readView
{
    if ([self.delegate respondsToSelector:@selector(readViewEndEdit:)]) {
        [self.delegate readViewEndEdit:self];
    }
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
}

//获取电量

- (CGFloat)getCurrentBatteryLevel
{
    UIApplication *app = [UIApplication sharedApplication];
    if (app.applicationState == UIApplicationStateActive||app.applicationState==UIApplicationStateInactive) {
        Ivar ivar=  class_getInstanceVariable([app class],"_statusBar");
        id status  = object_getIvar(app, ivar);
        for (id aview in [status subviews]) {
            int batteryLevel = 0;
            for (id bview in [aview subviews]) {
                if ([NSStringFromClass([bview class]) caseInsensitiveCompare:@"UIStatusBarBatteryItemView"] == NSOrderedSame&&[[[UIDevice currentDevice] systemVersion] floatValue] >=6.0) {
                    Ivar ivar=  class_getInstanceVariable([bview class],"_capacity");
                    if(ivar) {
                        batteryLevel = ((int (*)(id, Ivar))object_getIvar)(bview, ivar);
                        if (batteryLevel > 0 && batteryLevel <= 100) {
                            return batteryLevel;
                        } else {
                            return 0;
                        }
                    }
                }
            }
        }
    }
    return 0;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
